package glen.security.dao;

import glen.security.dto.Group;
import glen.security.dto.User;
import glen.security.dto.UserGroup;
import glen.util.TemplateDAO;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class GroupDAO extends TemplateDAO<Group, Integer> {

    public GroupDAO() {
        super(Group.class);

    }

    public GroupDAO(Class<Group> type) {
        super(type);

    }

    public GroupDAO(Class<Group> type, SqlSessionFactory sf) {
        super(type, sf);

    }

    public List<User> searchUserGroup(Integer groupId) {
        SqlSession session = sf.openSession();
        List<User> list = null;
        try {
            list = session.selectList("Group.searchUserGroup", groupId);
        } finally {
            session.close();
        }
        return list;
    }

    public List<User> listUser(Integer groupId) {
        SqlSession session = sf.openSession();
        List<User> list = null;
        try {
            list = session.selectList("Group.listUser", groupId);
        } finally {
            session.close();
        }
        return list;
    }

    public void saveUserGroup(Integer groupId, List<User> userList) {
        SqlSession session = sf.openSession();

        try {
            session.delete("Group.deleteUserGroup", groupId);
            for (User user : userList) {
                UserGroup userGroup = new UserGroup();
                userGroup.setGroupId(groupId);
                userGroup.setUserId(user.getUserId());
                session.insert("Group.addUserGroup", userGroup);
            }

            session.commit();
        } finally {
            session.close();
        }

    }

    public void deleteUserGroup(Integer groupId) {
        SqlSession session = sf.openSession();

        try {
            session.delete("Group.deleteUserGroup", groupId);
            session.commit();
        } finally {
            session.close();
        }

    }

}
